#!/usr/bin/env python
# -*- coding:utf-8 -*-
import serial  # 导入串口包
import time  # 导入时间包
import pymysql
import datetime
ser = serial.Serial("COM2", 115200, timeout=5)  # 开启com3口，波特率115200，超时5
ser.flushInput()  # 清空缓冲区
def uart_read():
    while True:
        count = ser.inWaiting()  # 获取串口缓冲区数据
        if count != 0:
            res = ser.read(ser.in_waiting).decode("utf-8")  # 读出串口数据，数据采用gbk编码
            print('串口向上位机位机发送数据为:' + res)  # 打印一下子
            time.sleep(0.1)  # 延时1秒，免得CPU出问题
            db = pymysql.connect(host='localhost', user='root', password='123456', db='ruqin', port=3306, charset='utf8')
            print('链接成功')

            # ttime = datetime.datetime.now()
            #
            # data = res
            # result = [ttime, data]
            if len(res) == 2:
                ttime = datetime.datetime.now()
                data = res
                result = [ttime, data]
                conn = db.cursor()  # 获取光标
                conn.execute('insert into app01_shuju2(time,data) values(%s,%s)', result)
                db.commit()
                conn.close()
                db.close()
                print('入表2')
            else:
                ttime = datetime.datetime.now()
                data1 = res
                result = [ttime, data1]
                conn = db.cursor()  # 获取光标
                conn.execute('insert into app01_shuju1(time,data) values(%s,%s)', result)
                db.commit()
                conn.close()
                db.close()
                print('入表1')
            # conn = db.cursor()  # 获取光标
            # conn.execute('insert into history(time,data,data2) values(%s,%s,%s)', result)
            # db.commit()
            # conn.close()
            # db.close()
            # print('OK')
            return res  # 返回读取的数
if __name__ == '__main__':
    while True:
        uart_read()
        time.sleep(2)